import requests from '../assets/requests'

function formatDate(date_timestamp) {
    let datetime = new Date()
    datetime.setTime(date_timestamp)
    let year = datetime.getFullYear()
    let month = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1
    let date = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate()
    let hour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours()
    let minute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes()
    let second = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds()
    return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second
}

function getRealtimeData(chip_id, startTime) {
    startTime = formatDate(startTime)
    console.log("Post:" + chip_id + " Start Time:" + startTime)
    console.log("Now is", new Date())
    return requests.post({
        url: '/realtime_api/device/report/gethrvDataList',
        data: {
            'chipid': chip_id,
            'start_time': startTime
        }
    }).then(response => {
        console.log(response)
        return response
    }).catch(error => {
        console.log(error.response)
    })
}

let setMyInterval = (fn, interval) => {
    let recurse, ref
    ref = {}
    ref["continue"] = true
    recurse = () => {
        if (ref["continue"]) {
            ref.timeout = setTimeout((() => {
                fn()
                recurse()
            }), interval)
        }
    }
    recurse()
    return ref
}

let clearMyInterval = (ref) => {
    ref["continue"] = false
    clearTimeout(ref.timeout)
}


const common = {}
common.getRealtimeData = getRealtimeData
common.formatDate = formatDate
common.setMyInterval = setMyInterval
common.clearMyInterval = clearMyInterval

export default common
